<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2020/09/20
 * Time: 16:08
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\system;


use app\admin\controller\BaseController;
use app\common\model\Countries;
use app\common\model\Exchange;
use think\facade\Validate;
use app\common\service\system\SystemService;

class ExchangeController extends BaseController
{
    /**
     * 汇率首页
     * @return string
     * @date 2020/09/20
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $exchange = Exchange::order("update_time desc")->select();
            $this->assign("list", $exchange);
            return $this->fetch("lists");
        }
        return $this->fetch("index");
    }

    /**
     * 添加汇率
     * @return array
     * @date 2020/09/20
     * @author longli
     */
    public function add()
    {
        $this->assign("currency", Countries::field(['currency_code', 'currency_name'])->group('currency_code')->select());
        $exchangeId = $this->request->request("exchange_id");
        if(!empty($exchangeId)) $this->assign("exchange", Exchange::get($exchangeId));
        return $this->fetch("add");
    }

    /**
     * 更新汇率信息
     * @return array
     * @date 2020/09/20
     * @author longli
     */
    public function update()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'source_code'  => 'require',
                'target_code'  => 'require',
                'rate'  => 'require|float|gt:0',
            ],[
                'source_code.require' => '源币种必选',
                'target_code.require' => '兑换币种必选',
                'rate.require' => '兑换比例必填',
                'rate.float' => '兑换比例必需是小数',
                'rate.gt' => '兑换比例必需大于0',
            ]);
            $data = $this->request->post();
        }
        else
        {
            $validate = Validate::make([
                'exchange_id'  => 'require',
            ],[
                'exchange_id.require' => '非法请求',
            ]);
            $data = $this->request->get();
        }
        if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        SystemService::getInstance()->addExchange($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 删除汇率
     * @return array
     * @date 2020/09/20
     * @author longli
     */
    public function delete()
    {
        $exchangeId = $this->request->request("ids");
        if(empty($exchangeId)) $this->error('参数错误');
        Exchange::destroy($exchangeId);
        $this->success('删除成功');
    }
}